﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography;
using System.Text;
using ImageServer.Util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;

namespace ImageServer.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UserController(ApplicationDbContext context, IConfiguration configuration) : ControllerBase
    {
        [HttpGet("{id:int}")]
        public IActionResult GetUserById(int id)
        {
            var user = context.User.Find(id);
            if (user == null)
            {
                return NotFound();
            }
            return Ok(user);
        }
        [HttpPost("register", Name = "RegisterUser")]
        public IActionResult RegisterUser([FromBody] RegisterRequest registerRequest)
        {
            // 检查用户名是否已存在
            if (context.User.Any(u => u.Name == registerRequest.Name))
            {
                return Conflict("User already exists.");
            }
            registerRequest.Password = PasswordHasher.CalculateSHA256(registerRequest.Password);
            var user = new User{ Name = registerRequest.Name, Password = registerRequest.Password };
            context.User.Add(user);
            context.SaveChanges();
            return CreatedAtAction(nameof(GetUserById), new { id = user.Id }, user);
        }
        [HttpPost("login", Name = "LoginUser")]
        public IActionResult LoginUser([FromBody] LoginRequest loginRequest)
        {
            var userInDb = context.User.FirstOrDefault(u => u.Name == loginRequest.Name);
            if (userInDb == null)
            {
                return NotFound("User not found.");
            }
            var hashedPassword = PasswordHasher.CalculateSHA256(loginRequest.Password);
            if (userInDb.Password != hashedPassword)
            {
                return Unauthorized("Invalid password.");
            }
            // 生成 JWT 令牌（假设你有一个 JWT 生成方法）
            var token = GenerateJwtToken(userInDb);
            // 返回令牌和用户信息
            return Ok(new { Token = token });
        }
        [HttpPut("{id}")]
        public IActionResult UpdateUser(int id, User user)
        {
            if (id != user.Id)
            {
                return BadRequest();
            }

            user.Password = PasswordHasher.CalculateSHA256(user.Password);
            context.Entry(user).State = EntityState.Modified;
            context.SaveChanges();
            return NoContent();
        }
        private string GenerateJwtToken(User user)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Name),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim("UserId", user.Id.ToString()),
                new Claim("UserName",user.Name)
            };
            var token = new JwtSecurityToken(
                issuer: configuration["Jwt:Issuer"],
                audience: configuration["Jwt:Audience"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(int.Parse(configuration["Jwt:LifetimeMinutes"])),
                signingCredentials: credentials
            );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
        [HttpGet("profile")]
        [Authorize]
        public IActionResult GetProfile()
        {
            var username = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            var user = context.User.FirstOrDefault(u => u.Name == username);
            if(user == null)
            {
                return NotFound();
            }
            // 返回用户信息不包含密码和 ID
            return Ok(new { user.Name});
        }
    }
    public class LoginRequest
    {
        public string Name { get; set; }
        public string Password { get; set; }
    }
    public class RegisterRequest
    {
        public string Name { get; set; }
        public string Password { get; set; }
    }
}